package user_service

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"bird/config"
	"bird/internal/pkg/core"
	"bird/pkg/utils"
	"go.uber.org/zap"
)

func (s *service) VerifyCode(ctx core.Context, phoneNo string) (vcode string, err error) {
	if !utils.CheckMobile(phoneNo) {
		return "", fmt.Errorf("非法的手机号")
	}

	redisKey := config.RedisKeyPrefixVerifyCode + phoneNo
	vcode = fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
	validMinutes := 5

	err = s.cache.Set(redisKey, vcode, time.Duration(validMinutes)*time.Minute)

	if err != nil {
		return
	}

	s.logger.Info("phone", zap.String("val", phoneNo))
	b, smsErr := s.sms.Send(phoneNo, vcode, strconv.Itoa(validMinutes))
	if smsErr != nil {
		s.logger.Warn("sms-return", zap.String("errmsg", string(b)))
		return vcode, smsErr
	}

	return vcode, nil
}
